/// API服务类
/// 
/// 封装API请求的通用方法
/// 自动处理数据模型转换
/// 
/// 作者: Fluttert Team
/// 日期: 2024

import '../core/network/api_client.dart';
import '../models/base_model.dart';

/// API服务类
/// 
/// 提供简化的API调用接口
/// 自动将响应数据转换为对应的模型对象
class ApiService {
  /// API客户端实例
  final ApiClient _client = ApiClient.instance;

  /// GET请求，返回单个模型对象
  /// 
  /// [T] 继承自BaseModel的模型类型
  /// [endpoint] API端点路径
  /// [queryParameters] 查询参数
  /// [fromJson] JSON转换函数
  /// 返回解析后的模型对象
  Future<T> get<T extends BaseModel>(
    String endpoint, {
    Map<String, dynamic>? queryParameters,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    final response = await _client.get(
      endpoint,
      queryParameters: queryParameters,
    );
    return fromJson(response.data as Map<String, dynamic>);
  }

  /// GET请求，返回模型对象列表
  /// 
  /// [T] 继承自BaseModel的模型类型
  /// [endpoint] API端点路径
  /// [queryParameters] 查询参数
  /// [fromJson] JSON转换函数
  /// 返回解析后的模型对象列表
  Future<List<T>> getList<T extends BaseModel>(
    String endpoint, {
    Map<String, dynamic>? queryParameters,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    final response = await _client.get(
      endpoint,
      queryParameters: queryParameters,
    );
    final List<dynamic> dataList = response.data as List<dynamic>;
    return dataList.map((json) => fromJson(json as Map<String, dynamic>)).toList();
  }

  /// POST请求，创建资源
  /// 
  /// [T] 继承自BaseModel的模型类型
  /// [endpoint] API端点路径
  /// [data] 请求体数据
  /// [fromJson] JSON转换函数
  /// 返回解析后的模型对象
  Future<T> post<T extends BaseModel>(
    String endpoint, {
    dynamic data,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    final response = await _client.post(
      endpoint,
      data: data,
    );
    return fromJson(response.data as Map<String, dynamic>);
  }

  /// PUT请求，更新资源
  /// 
  /// [T] 继承自BaseModel的模型类型
  /// [endpoint] API端点路径
  /// [data] 请求体数据
  /// [fromJson] JSON转换函数
  /// 返回解析后的模型对象
  Future<T> put<T extends BaseModel>(
    String endpoint, {
    dynamic data,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    final response = await _client.put(
      endpoint,
      data: data,
    );
    return fromJson(response.data as Map<String, dynamic>);
  }

  /// DELETE请求，删除资源
  /// 
  /// [endpoint] API端点路径
  Future<void> delete(String endpoint) async {
    await _client.delete(endpoint);
  }
}

